package com.doctor.ui.consulting;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Toast;

import com.doctor.adapter.TechConsultingAdapter;
import com.doctor.adapter.TechConsultingAdapter.TechConsultingAdapterCallback;
import com.doctor.bean.DiseaseRecordBean;
import com.doctor.bean.DoctorBean;
import com.doctor.bean.PatientFileBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FileHelper;
import com.doctor.comm.FragmentHelper;
import com.doctor.comm.ImageHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.MyApplication;
import com.doctor.comm.DialogHelper.DialogSelectCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.TextUtil;
import com.doctor.database.DbOperator;
import com.doctor.net.NetUtil;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.R;
import com.doctor.ui.wxapi.MyWXApi;
import com.doctor.ui.wxapi.WXShare;
import com.doctor.view.PullToRefreshListView;
import com.doctor.view.PullToRefreshListView.OnRefreshListener;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.Tencent;
import com.tencent.wpa.WPA;

public class TechConsultingFrag extends BaseFragment{

	/**
	 * 技术咨询
	 */
	
	private TechConsultingFragCallback callback;
	
	private Context context;
	private String[] operation={"修改","删除","取消"};
	private PullToRefreshListView listView;
	private TechConsultingAdapter adapter;
	private View listFoot;
	private TextView footMore;
	private ProgressBar footProgress;
	private AddDualDiagGroupFrag addDualDiagGroupFrag;
	private ModifyDualDiagGroupFrag modifyDualDiagGroupFrag;
	private DoctorDetailFrag doctorDetailFrag;
	private SendEmailFrag sendEmailFrag;
	private LinearLayout addBtn;    //添加按钮
	private Set<Integer> set;       //存储被点击的位置
	private SendSmsFrag sendSmsFrag;
	//从第1行开始查询
	private int fromRow=0;
	private List<DoctorBean> beanList;
	private Tencent tencent;
	private QQAuth mQQAuth;
	//用户的省份、城市、县信息
	private String province, city, county;
	//微信发送病历资料类别
	private final String TYPE_RECORD = "病历资料";
	//微信发送病历图片类别
	private final String TYPE_PIC = "病历图片";
	//选择病历图片对话框
	private AlertDialog dialog;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		String[] region = DbOperator.getInstance(getActivity()).selectUserRegion();
		if (region != null) {
			province = region[0] != null && region[0].trim().length() > 0 ? region[0] : null;
			city = region[1] != null && region[1].trim().length() > 0 ? region[1] : null;
			county = region[2] != null && region[2].trim().length() > 0 ? region[2] : null;
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		context=getActivity();
		View view=inflater.inflate(R.layout.tech_consulting, container, false);
		initiaView(view);
		getData();
		
		callback.onTechConsulting();
		return view;
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	
	public interface TechConsultingFragCallback{
		public void onTechConsulting();
	}
	
	
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try {
			callback=(TechConsultingFragCallback) activity;
		} catch (ClassCastException e) {
			e.printStackTrace();
		}
	}
	
	protected void initiaView(View view){
		addBtn=(LinearLayout) view.findViewById(R.id.addBtn);
		addBtn.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				addDualDiagGroupFrag=null;
				addDualDiagGroupFrag=new AddDualDiagGroupFrag();
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, addDualDiagGroupFrag).addToBackStack(null).commit();
			}
		});
		
		listView=(PullToRefreshListView) view.findViewById(R.id.listView);
		listFoot=View.inflate(getActivity(), R.layout.listview_footer, null);
		footMore=(TextView) listFoot.findViewById(R.id.listview_foot_more);
		footProgress=(ProgressBar) listFoot.findViewById(R.id.listview_foot_progress);
		// 添加底部视图 必须在setAdapter前
		listView.addFooterView(listFoot);
		
		beanList=new ArrayList<DoctorBean>();
		fromRow=0;
		set=new HashSet<Integer>();
		adapter=new TechConsultingAdapter(context, beanList, new TechConsultingAdapterAchieve());
		listView.setAdapter(adapter);
		
		listView.setOnScrollListener(new OnScrollListener() {			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				listView.onScrollStateChanged(view, scrollState);		
				if (adapter.getCount()==0) {
					return;
				}
				//判断是否滚动到底部
				boolean scrollEnd=false;
				try {
					if (view.getPositionForView(listFoot)==view.getLastVisiblePosition()) {
						scrollEnd=true;
					}
				} catch (Exception e) {
					scrollEnd=false;
					e.printStackTrace();					
				}
				
				if (scrollEnd && scrollState==SCROLL_STATE_TOUCH_SCROLL) {
					//下拉刷新
					footMore.setText(R.string.loading_data);
					footProgress.setVisibility(View.VISIBLE);
					footMore.setVisibility(View.VISIBLE);
					fromRow=adapter.getCount();
					freshData(fromRow);
				}	
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				listView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
		listView.setOnRefreshListener(new OnRefreshListener() {			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				//上拉刷新
				listView.onRefreshComplete();
				fromRow=0;
				freshData(fromRow);
			}
		});
		
		freshData(fromRow);
	}	
	
	
	//刷新数据
	private final void freshData(final int fromRow){
		if (fromRow<=0) {
			adapter.clear();
			//上拉刷新后id从头开始计数
			this.fromRow=0;
			adapter.notifyDataSetChanged();
		}
		
		new Thread() {
			public void run() {
				try {
					sleep(DbOperator.delayTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				final List<DoctorBean> list=DbOperator.getInstance(context).selectDoctorData(fromRow, province, city, county);
				getActivity().runOnUiThread(new Runnable() {	
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (list!=null && list.size()>0) {
							for (DoctorBean bean : list) {
								adapter.addBean(bean);
							}
							adapter.notifyDataSetChanged();
						}
							
						footMore.setText(R.string.more);
						footMore.setVisibility(View.GONE);
						footProgress.setVisibility(View.GONE);
					}
				});
			}
		}.start();
	}	
	
	
	//实现adapter的接口
	private class TechConsultingAdapterAchieve implements TechConsultingAdapterCallback{
		@Override
		public void onClickTitle(Integer position) {
			// TODO Auto-generated method stub
			if (set.contains(position)) {
				set.clear();
				adapter.setCurrPosition(-1);
			} else {
				set.clear();
				set.add(position);
				adapter.setCurrPosition(position);
			}			
			adapter.notifyDataSetChanged();
		}
		
		@Override
		public void onLongClickTitle(final DoctorBean bean) {
			// TODO Auto-generated method stub
			DialogHelper.selectDialog(context, null, operation, new DialogSelectCallback() {					
				@Override
				public void onDialogSelected(int position) {
					// TODO Auto-generated method stub
					if (position==0) {
						//修改
						modifyDualDiagGroupFrag=null;
						modifyDualDiagGroupFrag=new ModifyDualDiagGroupFrag();
						Bundle bundle=new Bundle();
						bundle.putSerializable(ConstConfig.BEAN, bean);
						modifyDualDiagGroupFrag.setArguments(bundle);
						FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
						FragmentHelper.setFragSwitchAnimation(transaction);
						transaction.replace(R.id.frag_container, modifyDualDiagGroupFrag).addToBackStack(null).commit();
						
					} else if (position==1) {
						DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {								
							@Override
							public void onClicked(int position) {
								// TODO Auto-generated method stub
								if (position==1) {
									//删除
									int row=DbOperator.getInstance(context).deleteData(ConstConfig.DOCTOR_TABLE, bean.getId());
									if (row>0) {
										Toast.makeText(context, "删除成功！", Toast.LENGTH_SHORT).show();
										adapter.removeBean(bean);
										if (bean.getCid()>0) {
											ContentValues values=new ContentValues();
											values.put("_cid", bean.getCid());
											DbOperator.getInstance(context).insertData(ConstConfig.DELETED_DOCTOR_TABLE, values);
										}
									} else {
										Toast.makeText(context, "删除失败！", Toast.LENGTH_SHORT).show();
									}
								}
							}
						});
					}
				}
			});
		}

		@Override
		public void onClickPhone(String mobileNumber, String phoneNumber) {
			// TODO Auto-generated method stub
			TelephonyManager telManager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);			
			if (telManager.getSimState()==TelephonyManager.SIM_STATE_ABSENT) {
				Toast.makeText(context, "未插入SIM卡！", Toast.LENGTH_SHORT).show();
			} else if (telManager.getSimState()==TelephonyManager.SIM_STATE_READY) {
				if (null!=mobileNumber && !"".equals(mobileNumber)) {
					startActivity(new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+mobileNumber)));
				} else if (null!=phoneNumber && !"".equals(phoneNumber)) {
					startActivity(new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phoneNumber)));
				} else {
					Toast.makeText(context, "没有设置手机和电话！", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(context, "请确保SIM卡状态良好！", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onClickSms(String mobileNumber) {
			// TODO Auto-generated method stub
			TelephonyManager telManager=(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);	
			if (telManager.getSimState()==TelephonyManager.SIM_STATE_ABSENT) {
				Toast.makeText(context, "未插入SIM卡！", Toast.LENGTH_SHORT).show();
			} else if (telManager.getSimState()==TelephonyManager.SIM_STATE_READY){
				if (null!=mobileNumber && !"".equals(mobileNumber)) {
					FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
					sendSmsFrag=null;
					sendSmsFrag=new SendSmsFrag();
					Bundle bundle=new Bundle();
					bundle.putString("tel", mobileNumber);
					//fragment间传递手机号码数据
					sendSmsFrag.setArguments(bundle);
					FragmentHelper.setFragSwitchAnimation(transaction);
					transaction.replace(R.id.frag_container, sendSmsFrag).addToBackStack(null).commit();
				} else {
					Toast.makeText(context, "未填写手机！", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(context, "请确保SIM卡状态良好！", Toast.LENGTH_SHORT).show();
			}			
		}

		@Override
		public void onClickQQ(String qq) {
			// TODO Auto-generated method stub
			if (qq==null || "".equals(qq)) {
				Toast.makeText(context, "未填写qq号！", Toast.LENGTH_SHORT).show();
				return;
			}
			
			boolean isQqInstalled=FileHelper.isPkgInstalled(context, "com.tencent.mobileqq");
			if (!isQqInstalled) {
				Toast.makeText(context, "尚未安装QQ，无法启动！", Toast.LENGTH_SHORT).show();
				return;
			}
			tencent=Tencent.createInstance("101108930", getActivity().getApplicationContext());
			mQQAuth = QQAuth.createInstance("101108930", getActivity().getApplicationContext());
			WPA mWPA = new WPA(getActivity(),mQQAuth.getQQToken());
			mWPA.startWPAConversation(qq, "");
		}
		
		@Override
		public void onClickWx() {
			// TODO Auto-generated method stub
			if (!MyWXApi.canUseWX()) {
				LoadingTip.showToast(getActivity(), getString(R.string.wx_unuseful));
				return;
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.common_dialog);
			builder.setTitle("微信");
			builder.setIcon(R.drawable.alert_icon);
			builder.setSingleChoiceItems(new String[]{"微信聊天", "微信发送病历资料", "微信发送病历图片", "取消"}, -1, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					switch (arg1) {
					case 0:  //选中微信聊天
						WXShare.shareText(getString(R.string.wx_session_from_app));
						break;
						
					case 1: //选中微信发送病历资料
						selectAllPatients(TYPE_RECORD);
						LoadingTip.showDialog(getActivity(), null);
						break;

					case 2: //选中微信发送病历图片
						selectAllPatients(TYPE_PIC);
						LoadingTip.showDialog(getActivity(), null);
						break;	
						
					default:
						break;
					}
					arg0.dismiss();
				}
			});
			builder.setCancelable(true);
			builder.create().show();
		}
		

		@Override
		public void onClickEmail(String email) {
			// TODO Auto-generated method stub
			if (null!=email && !"".equals(email)) {
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				sendEmailFrag=null;
				sendEmailFrag=new SendEmailFrag();
				Bundle bundle=new Bundle();
				bundle.putString("email", email);
				sendEmailFrag.setArguments(bundle);
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, sendEmailFrag).addToBackStack(null).commit();
			} else {
				Toast.makeText(context, "未填写邮箱！", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onClickDetail(DoctorBean bean) {
			// TODO Auto-generated method stub
			doctorDetailFrag=null;
			doctorDetailFrag=new DoctorDetailFrag();
			Bundle bundle=new Bundle();
			bundle.putSerializable(ConstConfig.BEAN, bean);
			doctorDetailFrag.setArguments(bundle);
			FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
			FragmentHelper.setFragSwitchAnimation(transaction);
			transaction.replace(R.id.frag_container, doctorDetailFrag).addToBackStack(null).commit();
		}

		@Override
		public void onClickWebSite(String url) {
			// TODO Auto-generated method stub
			if (!NetUtil.hasNetwork(context)) {
				Toast.makeText(context, "请连接网络！", Toast.LENGTH_SHORT).show();
				return;
			}
			if (url==null || "".equals(url.trim())) {
				Toast.makeText(context, "未填写平台信息！", Toast.LENGTH_SHORT).show();
				return;
			}
			
			Intent intent = new Intent();        
	        intent.setAction("android.intent.action.VIEW");    
	        Uri content_url;
	        
			if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
				content_url = Uri.parse(url); 
			} else {
				content_url = Uri.parse("http://"+url); 
			}		
			intent.setData(content_url);            
	        startActivity(intent);
		}
		
	}
	
	
	/**
	 * 查询并显示所有的患者档案
	 * @param type 类型(病历资料或是病历图片)
	 */
	private void selectAllPatients(final String type) {
		new AsyncTask<String, Integer, List<PatientFileBean>>(){
			@Override
			protected List<PatientFileBean> doInBackground(String... arg0) {
				// TODO Auto-generated method stub
				return DbOperator.getInstance(MyApplication.getInstance()).selectAllPatientName();
			}
			
			@Override
			protected void onPostExecute(final List<PatientFileBean> result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.common_dialog);
				builder.setTitle("选择客户");
				builder.setIcon(R.drawable.alert_icon);
				if (result != null && !result.isEmpty()) {
					int count = result.size();
					String[] names = new String[count];
					for (int i = 0; i < count; i++) {
						names[i] = result.get(i).getName();
					}
					builder.setSingleChoiceItems(names, -1, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							arg0.dismiss();
							LoadingTip.showDialog(getActivity(), null);
							int patientId = result.get(arg1).getId();
							selectAllDiseaseRecord(patientId, type);
						}
					});
				} else {
					builder.setMessage("没有客户档案！");
					builder.setNegativeButton("确定", null);
				}
				LoadingTip.hideDialog();
				builder.setCancelable(true);
				builder.create().show();
			}
		}.execute("");
	}
	
	
	/**
	 * 查询并显示病历资料
	 * @param patientId 患者档案id
	 * @param type 病历资料或是病历图片类别
	 */
	private void selectAllDiseaseRecord(final int patientId, final String type) {
		new AsyncTask<Integer, Integer, List<DiseaseRecordBean>>(){
			@Override
			protected List<DiseaseRecordBean> doInBackground(Integer... arg0) {
				// TODO Auto-generated method stub
				return DbOperator.getInstance(MyApplication.getInstance()).selectAllDiseaseName(arg0[0]);
			}
			
			@Override
			protected void onPostExecute(final List<DiseaseRecordBean> result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.common_dialog);
				builder.setTitle("选择病历");
				builder.setIcon(R.drawable.alert_icon);
				if (result != null && !result.isEmpty()) {
					int count = result.size();
					String[] items = new String[count];
					for (int i = 0; i < count; i++) {
						items[i] = result.get(i).getComplain();
					}
					builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							int diseaseId = result.get(arg1).getId();
							DiseaseRecordBean diseaseRecord = DbOperator.getInstance(MyApplication.getInstance()).getDiseaseRecord(diseaseId);
							if (TYPE_RECORD.equals(type)) {
								//微信发送病历资料
								DiseaseRecordBean healthManage = DbOperator.getInstance(MyApplication.getInstance()).getDiseaseRecordHealthManagerById(diseaseId);
								if (diseaseRecord != null && healthManage != null) {
									diseaseRecord.setHealthAna(healthManage.getHealthAna());
									diseaseRecord.setHealthInstruct(healthManage.getHealthInstruct());
									diseaseRecord.setHealthDirect(healthManage.getHealthDirect());
								}
								PatientFileBean patientFile = DbOperator.getInstance(MyApplication.getInstance()).getPatientFile(patientId);
								arg0.dismiss();
								WXShare.sharePatientDiseaseRecord(patientFile, diseaseRecord);
								
							} else if (TYPE_PIC.equals(type)) {
								//微信发送病历图片
								arg0.dismiss();
								showDiseasePic(diseaseRecord.getImgage());
							}
						}
					});
				} else {
					builder.setMessage("没有病历资料！");
					builder.setNegativeButton("确定", null);
				}
				LoadingTip.hideDialog();
				builder.setCancelable(true);
				builder.create().show();
			}
		}.execute(patientId);
	}
	
	
	/**
	 * 弹出对话框显示选中的病历中的所有图片缩略图
	 * @param pics
	 */
	private void showDiseasePic(String pics) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.common_dialog);
		builder.setTitle("选择图片");
		builder.setIcon(R.drawable.alert_icon);
		Map<String, Bitmap> map = null;
		if (pics != null) {
			String[] array = pics.split(ConstConfig.IMAGE_SPLIT);
			if (array != null && array.length > 0) {
				map = new LinkedHashMap<>();
				for (String path : array) {
					Bitmap bitmap = ImageHelper.getThumbBitmap(path, 50, 50);
					if (bitmap != null) {
						map.put(path, bitmap);
					}
				}
			}
		}
		
		if (map != null && !map.isEmpty()) {
			OnClickListener onClick = new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					String path = (String) arg0.getTag();
					WXShare.sharePic(path);
					dialog.dismiss();
				}
			};
			
			View view = View.inflate(getActivity(), R.layout.choose_disease_pic_dialog, null);
			LinearLayout container = (LinearLayout) view.findViewById(R.id.ll_container);
			int i = 0;
			for (String path : map.keySet()) {
				LinearLayout item = (LinearLayout) container.getChildAt(i);
				item.setVisibility(View.VISIBLE);
				ImageView ivPic = (ImageView) item.getChildAt(1);
				ivPic.setImageBitmap(map.get(path));
				item.setTag(path);
				item.setOnClickListener(onClick);
				i++;
			}
			builder.setView(view);
			
		} else {
			builder.setMessage("该病历没有图片！");
			builder.setNegativeButton("确定", null);
		}
		
		builder.setCancelable(true);
		dialog = builder.create();
		dialog.show();
	}
}
